import fg from "fast-glob";
import fs from "fs-extra";
import { toolchain } from "../toolchain.js";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";

export class TmpMatSorter {
    async start(): Promise<void> {
        const legacyUI = toolchain.opts.cfg!.legacyUI!;
        const pattern = legacyUI.filter(v => !v.startsWith('^')).map(v => '**/' + v + '.prefab');
        const ignore = legacyUI.filter(v => v.startsWith('^')).map(v => '**/' + v.substring(1) + '.prefab');

        const mat = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/font/ttf/common/gameFont2/gameFont2_Direction_TMP.mat');
        const matGUID = await UnityHelper.readGUID(mat + '.meta');

        const targetMat = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/font/ttf/common/gameFont2/gameFont2_BlackOutline2_0.5.mat');
        const targetMatGUID = await UnityHelper.readGUID(targetMat + '.meta');

        const uiRoot = path.join(toolchain.opts.projectRoot, 'Assets/AssetSources/ui');
        // const prefabs = await fg(pattern, { cwd: uiRoot, ignore });
        const prefabs = await fg('**/*.prefab', { cwd: uiRoot });
        for (const p of prefabs) {
            const pfile = path.join(uiRoot, p);
            const content = await fs.readFile(pfile, 'utf-8');
            const newContent = content.replaceAll(matGUID, targetMatGUID);
            if (newContent != content) {
                await fs.writeFile(pfile, newContent, 'utf-8');
                console.log(`${p} modified`);
            }
        }
    }
}